<template>
  <div class="panel">
    <el-dialog :title="action==='add'?'添加产品':'修改产品'" :visible.sync="visible" width="800px" @opened="opened" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="所属分类"  prop="pid">
          <el-select v-model="form.pid" placeholder="所属分类" ref="pid"  class="state" clearable>
            <el-option v-for="item in cateOptions" :key="item.id" :value="item.id" :label="item.title"></el-option>
         </el-select>
        </el-form-item>
        <el-form-item label="产品标题" prop="title">
          <el-input v-model.trim="form.title"></el-input>
        </el-form-item>
        <el-form-item label="产品摘要">
          <el-input v-model.trim="form.summary"></el-input>
        </el-form-item>
        <el-form-item label="产品单价" prop="price">
          <el-input-number v-model.number="form.price"></el-input-number>
        </el-form-item>
        <el-form-item label="上传产品图" prop="picture">
          <el-tooltip  effect="dark" content="请上传150*100的图片" placement="right-start" style="display: inline-block">
            <el-upload
              class="mypicture"
              action="http://cloud.scnew.com.cn/api/user/upload"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload">
              <img v-if="form.picture" :src="form.picture">
              <i v-else class="el-icon-plus"></i>
            </el-upload>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="产品库存" prop="total">
          <el-input-number v-model.number="form.total"></el-input-number>
        </el-form-item>
        <el-form-item label="产品内容" prop="content">
          <mavon-editor v-model="form.content"/>
        </el-form-item>
        <el-form-item label="审核" >
          <el-switch v-model="form.state" active-color="#13ce66" :active-value="2" :inactive-value="1"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <div class="heading">
      <h1>产品列表</h1>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/app">首页</el-breadcrumb-item>
        <el-breadcrumb-item to="/app/product">产品管理</el-breadcrumb-item>
        <el-breadcrumb-item>产品列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="search">
      <div class="condition">
        <el-button v-if="ids.length" type="danger" size="small" @click="del(ids)">批量删除</el-button>
        <el-select v-model="condition.state" placeholder="是否审核" size="small" class="state" clearable>
          <el-option :value="2" label="审核"></el-option>
          <el-option :value="1" label="未审核"></el-option>
         </el-select>
        <el-select v-model="condition.pid" placeholder="所属分类" size="small" class="state" clearable>
          <el-option v-for="item in cateOptions" :key="item.id" :value="item.id" :label="item.title"></el-option>
         </el-select>
         <el-select v-model="condition.price" placeholder="价格范围" size="small" class="state" clearable>
          <el-option value="0-99" label="0 ~ 99元" />
          <el-option value="100-999" label="100 ~ 999元" />
          <el-option value="1000-9999" label="1000 ~ 9999元" />
          <el-option value="10000-99999" label="10000 ~ 99999元" />
         </el-select>

        <el-input v-model="condition.keyword" placeholder="请输入产品标题" size="small" clearable class="keyword" ></el-input>
      </div>
      <el-button type="success" size="small" @click="add">新增</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" prop="id"></el-table-column>
      <el-table-column prop="pid" label="分类" width="120" :formatter="formatPid"></el-table-column>
      <el-table-column label="缩略图" width="150">
        <template v-slot="scope">
          <img  :src="scope.row.picture" height="55" />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="180"></el-table-column>
      <el-table-column prop="price" label="单价" width="120"></el-table-column>
      <el-table-column prop="total" label="库存" width="120"></el-table-column>
      <el-table-column label="审核">
        <template v-slot="scope">
          <el-switch v-model="scope.row.state" active-color="#13ce66" :active-value="2"
          :inactive-value="1" @change="stateChange($event,scope.row.id)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="160">
        <template v-slot="scope">
          <el-button size="mini" plain @click="updata(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="del([scope.row.id])">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total, prev, pager, next"
    :page-size="condition.pageSize" :total="total" :current-page.sync="condition.page"
    class="mypage">
    </el-pagination>
  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
export default {
  components: { mavonEditor },
  data () {
    return {
      action: null,
      visible: false,
      form: {},
      loading: true,
      condition: { page: 1, pageSize: 3 },
      tableData: [],
      cateOptions: [],
      total: 0,
      ids: [],
      rules: {
        pid: [
          { required: true, message: '请选择所属分类' }
        ],
        title: [
          { required: true, message: '请输入产品标题' }
        ],
        price: [
          { required: true, message: '请输入产品价格' }
        ],
        picture: [
          { required: true, message: '请选择产品图片' }
        ],
        total: [
          { required: true, message: '请输入产品库存' }
        ]
      }
    }
  },
  created () {
    this.query()
    this.queryCate()
  },
  watch: {
    condition: {
      handler () {
        this.query()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    opened () {
      this.$refs.pid.focus()
    },
    save () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 添加保存时
          if (this.action === 'add') {
            this.$http.post('product/add', { ...this.form }).then(res => {
              if (res.err > 0) {
                this.$message.error(res.desc)
              } else {
                this.$message.success(res.desc)
                if (this.condition.page === 1) {
                  this.query()
                } else {
                  this.condition.page = 1
                }
                this.visible = false
              }
            })
          } else if ((this.action === 'updata')) { // 修改保存时
            this.$http.post('product/updata', { ...this.form }).then(res => {
              if (res.err > 0) {
                this.$message.error(res.desc)
              } else {
                this.$message.success(res.desc)
                this.query()
                this.visible = false
              }
            })
          }
        }
      })
    },
    query () {
      this.$http.get('product/list', { params: this.condition }).then(res => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        } else {
          this.tableData = res.result
          this.total = res.total
          this.condition.page = res.page
          setTimeout(() => { this.loading = false }, 500)
        }
      })
    },
    queryCate () {
      this.$http.get('productcate/classify').then(res => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        } else {
          this.cateOptions = res.result
        }
      })
    },
    add () {
      this.action = 'add'
      this.visible = true
      this.form = { price: 9999, total: 999 }
    },
    updata (row) {
      this.action = 'updata'
      this.visible = true
      this.form = { ...row, password: '' }
    },
    del (ids) {
      this.$confirm('你确定要删除吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post('product/delete', { ids }).then(res => {
          if (res.err > 0) {
            this.$message.error(res.desc)
          } else {
            this.$message.success(res.desc)
            this.query()
          }
        })
      }).catch(() => {})
    },
    stateChange (state, id) {
      this.$http.post('product/state', { id, state }).then(res => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        } else {
          this.$message.success(res.desc)
        }
      })
    },
    handleSelectionChange (row) {
      this.ids = row.map(item => item.id)
    },
    beforeUpload (file) {
      const type = file.type.split('/')[1].toLowerCase()
      const isPic = ['jpeg', 'png', 'gif', 'jpg', 'webp']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isPic.includes(type)) {
        this.$message.error('上传图片只能是 ' + isPic + ' 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPic && isLt2M
    },
    uploadSuccess (res) {
      if (res.err > 0) {
        this.$message.error(res.desc)
      } else {
        this.$message.success(res.desc)
        this.$set(this.form, 'picture', res.result)
      }
    },
    formatPid (row) {
      return this.cateOptions.find(item => item.id === row.pid)?.title || '未知'
    }
  }
}
</script>

<style lang="less">
  .mypicture{
    .el-upload {
      border: 1px solid #DCDFE6;
      border-radius: 4px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #0fecec;
      }
      img{
        display: block;
        width: 150px;
        height: 100px;
      }
      [class*="el-icon-"]{
        width: 150px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        font-size: 24px;
        color: #8c939d;
      }
    }
  }
</style>
